package com.light.mytext.thread

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.light.mytext.R
import kotlinx.android.synthetic.main.activity_callable_future.*
import java.util.concurrent.Callable
import java.util.concurrent.FutureTask

/**
 * 创建线程的方式
 * 一、继承Thread类
 * 二、实现Runable接口
 * 三、Callable+Future
 */
class CallableFutureActivity : AppCompatActivity(), View.OnClickListener {

    private var task: FutureTask<Int>?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_callable_future)
        init_Listener()
        init()
    }

    fun init() {
         task = FutureTask<Int>(
            Callable<Int> {
                var i = 0
                while (i < 100) {
                    Log.i("CallableFuture==",Thread.currentThread().name + "的循环变量主的值:" + i)
                    i++
                }
                i
            } as Callable<Int>?
        )


    }

    fun init_Listener() {
        tv_start.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_start -> {
                Thread(task,"有返回值的线程").start()
                try {
                    //获取线程返回值
                    Log.i("CallableFuture==","子线程返回的值:" + task!!.get())
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }

            }
        }
    }

}